package com.sanjin.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.sanjin.mall.common.constant.ProductConstant;
import com.sanjin.mall.common.es.SkuEsModel;
import com.sanjin.mall.common.utils.R;
import com.sanjin.mall.product.entity.*;
import com.sanjin.mall.product.feign.MallSearch;
import com.sanjin.mall.product.feign.MallWareHouse;
import com.sanjin.mall.product.service.*;
import com.sanjin.mall.product.vo.SkuHasStockVo;
import com.sanjin.mall.product.vo.SpuSaveVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanjin.mall.common.utils.PageUtils;
import com.sanjin.mall.common.utils.Query;

import com.sanjin.mall.product.dao.SpuInfoDao;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    ProductAttrValueServiceImpl attrValueService;
    @Autowired
    AttrService attrService;
    @Autowired
    MallWareHouse wareHouse;
    @Autowired
    MallSearch search;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

    }

    @Override
    public void up(Long spuId) {

        //1.查出当前 spuid 对应的所有 sku信息、品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO  4、查询当前sku的所有可以用来被检索的规格属性，
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> { //返回所有属性的id
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);//因为是kv 键值对，转换成 set 集合比较方便

        // 从  baseAttrs 集合中 过滤 出  attrValueEntities 集合
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> { //将 set集合 映射 成  map集合
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);//属性对拷：item 是数据库中查出来的数据
            return attrs;
        }).collect(Collectors.toList());

        //TODO 1、发送远程调用，库存系统查询是否有库存
        //由于远程调用可能出现网络问题，所以需要进行try  - catch处理一下
        Map<Long, Boolean> stockMap = null;
        try {
            R r = wareHouse.getSkuHasStock(skuIdList);

            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>(){

            };
            List<SkuHasStockVo> data = r.getData(typeReference);
            for (int i = 0; i <data.size(); i++) {
                stockMap.put(data.get(i).getSkuId(), data.get(i).getHasStock());
            }
        }catch (Exception e){
            log.error("库存服务查询异常：原因{}",e);
        }


        //2.封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {//通过  stream API 将 skus中的 数据遍历
            //组装我们需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);//属性对拷，将 sku中的属性 拷贝到 esmodel中

            //需要单独处理的数据 ，SkuInfoEntity 和 SkuEsModel中相比少的数据。
            //skuPrice,skuImg

            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //hotScore(热度评分)  hasStock(库存)

            //设置库存信息
            //如果远程调用出现问题，默认给 true值；如果没有问题，那就赋真正的值
            if (finalStockMap == null){
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //TODO 2、热度评分。0
            esModel.setHotScore(0L);//这里的热度评分应该是一个比较复杂的操作，这里简单处理一下

            //TODO 3、查询品牌和分类的名字信息
            //品牌
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            //分类
            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());

            //设置检索属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());


        //TODO 5、将数据发送给 es 进行保存，gulimall-search
        R r = search.productStatusUp(upProducts);
        if (r.getCode() == 0){
            //远程调用成功
            //TODO 6、修改当前spu的状态
            baseMapper.updataSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO  7、重复调用？接口幂等性；重试机制？ xxx

            //Feign 调用流程
            /**
             * 1.构造请求数据，将对象转为json；
             * RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 2.发送请求进行执行（执行成功会解码响应数据）；
             * executeAndDecode(template)'
             * 3.执行请求会有重试机制
             * while(true){
             *    try{
             *      executeAndDecode(template);
             *    }catch(){
             *       try{ retryer.continueOrPropagate(e);}catch(){throw ex;
             *       continue;
             *          }
             *    }
             *
             */

        }

    }


}